package com.lzy.shiro;

import cn.hutool.core.bean.BeanUtil;
import com.lzy.entity.User;
import com.lzy.service.UserService;
import com.lzy.util.JwtUtils;
import jdk.nashorn.internal.parser.Token;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @autor shkstart
 * @create 2021-01-14 11:13)
 */
@Slf4j
@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserService userService;
    /**
     * 判断token是否是Jwtfilter中封装的jwtToken
     * 大坑，必须重写此方法，不然Shiro会报错
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    //权限配置
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //进行身份认证,判断用户名密码是否匹配正确
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        JwtToken jwtToken = (JwtToken) authenticationToken;

        log.info("jwt----------------->{}", jwtToken.toString());
        //登录时存放了用户id到token中
        String userId = jwtUtils.getClaimByToken((String)jwtToken.getPrincipal()).getSubject();

        User user = userService.getById(Long.valueOf(userId));
        if(user == null){
            throw new UnknownAccountException("账户不存在"); //未知账号
        }

        if(user.getStatus() == -1){
            throw new DisabledAccountException("账户已被锁定"); //帐号禁
        }
        AccountPfofile accountPfofile = new AccountPfofile();
        BeanUtil.copyProperties(user,accountPfofile);
        log.info("accountPfofile----------------->{}", accountPfofile.toString());
        return new SimpleAuthenticationInfo(accountPfofile,jwtToken.getCredentials(),getName());
    }
}
